package com.jy.authors.service.impl;

import java.util.List;

import com.jy.books.domain.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.jy.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.jy.authors.mapper.AuthorsMapper;
import com.jy.authors.domain.Authors;
import com.jy.authors.service.IAuthorsService;

/**
 * 作者Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class AuthorsServiceImpl implements IAuthorsService 
{
    @Autowired
    private AuthorsMapper authorsMapper;

    /**
     * 查询作者
     * 
     * @param authorId 作者主键
     * @return 作者
     */
    @Override
    public Authors selectAuthorsByAuthorId(Long authorId)
    {
        return authorsMapper.selectAuthorsByAuthorId(authorId);
    }

    /**
     * 查询作者列表
     * 
     * @param authors 作者
     * @return 作者
     */
    @Override
    public List<Authors> selectAuthorsList(Authors authors)
    {
        return authorsMapper.selectAuthorsList(authors);
    }

    /**
     * 新增作者
     * 
     * @param authors 作者
     * @return 结果
     */
    @Transactional
    @Override
    public int insertAuthors(Authors authors)
    {
        int rows = authorsMapper.insertAuthors(authors);
        insertBooks(authors);
        return rows;
    }

    /**
     * 修改作者
     * 
     * @param authors 作者
     * @return 结果
     */
    @Transactional
    @Override
    public int updateAuthors(Authors authors)
    {
        authorsMapper.deleteBooksByAuthorId(authors.getAuthorId());
        insertBooks(authors);
        return authorsMapper.updateAuthors(authors);
    }

    /**
     * 批量删除作者
     * 
     * @param authorIds 需要删除的作者主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteAuthorsByAuthorIds(Long[] authorIds)
    {
        authorsMapper.deleteBooksByAuthorIds(authorIds);
        return authorsMapper.deleteAuthorsByAuthorIds(authorIds);
    }

    /**
     * 删除作者信息
     * 
     * @param authorId 作者主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteAuthorsByAuthorId(Long authorId)
    {
        authorsMapper.deleteBooksByAuthorId(authorId);
        return authorsMapper.deleteAuthorsByAuthorId(authorId);
    }

    /**
     * 新增书籍管理信息
     * 
     * @param authors 作者对象
     */
    public void insertBooks(Authors authors)
    {
        List<Books> booksList = authors.getBooksList();
        Long authorId = authors.getAuthorId();
        if (StringUtils.isNotNull(booksList))
        {
            List<Books> list = new ArrayList<Books>();
            for (Books books : booksList)
            {
                books.setAuthorId(authorId);
                list.add(books);
            }
            if (list.size() > 0)
            {
                authorsMapper.batchBooks(list);
            }
        }
    }
}
